package pub.tbc.api;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.cache.CacheProvider;
import pub.tbc.api.cache.ServiceCache;
import pub.tbc.api.config.ProjectConfig;
import pub.tbc.api.service.initalize.ServiceCacheInitializer;
import pub.tbc.api.service.initalize.ServiceCacheInitializerProvider;
import pub.tbc.api.util.Banner;

import java.util.List;

/**
 * @author tbc on 2017/3/1 18:03:14.
 */
@Slf4j
public class ApiGatewayApplication {

    private void banner(ProjectConfig projectConfig) {
        if (projectConfig.printBanner())
            new Banner().print();
    }

    /**
     * 初始化服务地址
     */
    private void serviceInit() {
        ServiceCacheInitializer init = ServiceCacheInitializerProvider.getServiceCacheInitialize();
        init.initServiceCache();
        ServiceCache serviceCache = CacheProvider.getServiceCache();
        serviceCache.services().forEach(key -> System.out.println(serviceCache.get(key)));
    }

    /**
     * 项目初始化
     *
     * @param projectConfig
     */
    private void init(ProjectConfig projectConfig) {
        // banner print
        banner(projectConfig);
        // 服务缓存初始化
        serviceInit();
        // 配置初始化
    }

    private void start(ProjectConfig projectConfig) {
        init(projectConfig);

        // 创建netty server
        HttpNettyServer httpNettyServer = () -> new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                List<ChannelHandler> handlers = HandlerFactory.handlers();
                handlers.forEach(handler -> {
                    log.debug("add handler ===> {}", handler.getClass().getName());
                    ch.pipeline().addLast(handler);
                });
            }
        };

        // 开始监听端口，启动完毕
        int port = projectConfig.httpPort();
        httpNettyServer.bind(port);
        log.info("ApiGateway started, listener port: {}", port);
    }

    public static void main(String[] args) {
        new ApiGatewayApplication().start(ProjectConfig.instance());
    }


}
